package com.demo.fulllink.service.impl;

import com.demo.fulllink.common.emum.ResponseErrorEnum;
import com.demo.fulllink.common.utils.CommonUtils;
import com.demo.fulllink.mapper.NotifyMapper;
import com.demo.fulllink.mapper.OrderMapper;
import com.demo.fulllink.mapper.ProductMapper;
import com.demo.fulllink.module.po.OrderPO;
import com.demo.fulllink.module.vo.OrderVO;
import com.demo.fulllink.module.vo.ProductVO;
import com.demo.fulllink.module.vo.ResponseVO;
import com.demo.fulllink.service.OrderDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

@Service
public class OrderDBServiceImpl implements OrderDBService {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private NotifyMapper notifyMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    public OrderPO findById(Serializable id) {
        return orderMapper.findById(id);
    }
    
    @Override
    public void insert(OrderPO orderPO) {
        orderMapper.insert(orderPO);
    }
    
    @Override
    public void updateById(OrderPO orderPO) {
        orderMapper.updateById(orderPO);
    }
    
    @Transactional
    public ResponseVO actualPlaceOrder(OrderVO orderVO) {
        if (null != orderVO) {
            //删除Redis KEY 幂等性校验
            boolean flag = redisTemplate.delete(CommonUtils.getOrderIdempotentKey(orderVO.getId()));
            //删除成功进真实库存扣减
            if (flag) {
                //乐观锁真实库存扣减
                int num = productMapper.deductionStock(toProductVO(orderVO));
                //扣减成功
                if (num > 0) {
                    //更新订单状态
                    orderVO.setStatus(2);
                    orderMapper.updateById(orderVO);
                    return ResponseVO.success("下单成功");
                }
                return ResponseErrorEnum.STOCK_ERROR.toResponseVO();
            } else {
                return ResponseErrorEnum.REPEAT_REQUEST_ERROR.toResponseVO();
            }
        }
        return ResponseErrorEnum.ORDER_ERROR.toResponseVO();
    }
    
    @Override
    public void removeAll() {
        orderMapper.removeAll();
        notifyMapper.removeAll();
    }
    
    /**
     * 转换为 产品VO
     *
     * @param orderVO
     * @return
     */
    private ProductVO toProductVO(OrderVO orderVO) {
        ProductVO productVO = new ProductVO();
        productVO.setId(orderVO.getProductId());
        productVO.setBayNum(orderVO.getProductNum());
        productVO.setVersion(orderVO.getProductVersion());
        return productVO;
    }
    
}
